package com.xinqi.common.mybatis.type;

import com.fasterxml.jackson.databind.JsonNode;
import com.xinqi.common.base.utils.json.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JsonNode转换
 */
public class JsonNodeTypeHandler extends BaseTypeHandler<JsonNode> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType)
        throws SQLException {
        ps.setString(i, parameter.toString());
    }

    @Override
    public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return toJsonNode(result);
    }

    @Override
    public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return toJsonNode(result);
    }

    @Override
    public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return toJsonNode(result);
    }

    private JsonNode toJsonNode(String s) {
        if (s == null) {
            return null;
        }
        try {
            return JSON.reader().readTree(s);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot convert [ " + s + " ] to JsonNode.", e);
        }
    }

}
